/**
 * 
 */
package com.ys.ylideas.schedule;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.ys.ylideas.YlIdeasApplication;
import com.ys.ylideas.entity.IdeaEntity;
import com.ys.ylideas.entity.UserEntity;
import com.ys.ylideas.service.AccountService;
import com.ys.ylideas.service.IdeaService;
import com.ys.ylideas.util.HttpRequest;

/**
 * @author Red 定时任务，同步用户信息
 */

@Component
public class UpdateInfoTask {

	private static final Logger logger = LoggerFactory.getLogger(YlIdeasApplication.class);
	private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	@Autowired
	private AccountService accountService;

	@Autowired
	private IdeaService ideasService;

	// 午夜0时执行
	@Scheduled(cron="0 0 0 * * ?")	
	public void UploadIdeasTask() {
		Date date = new Date();
		logger.info("Start to update all users' uploaded ideas at " + sdf.format(date));

		List<Long> userIds = accountService.getAllUserId();

		if (userIds.size() == 0) {
			logger.info("There is no user in our system");
		} else {
			logger.info("Total users number is " + userIds.size());
			for (int i = 0; i < userIds.size(); i++) {
				long accountId = userIds.get(i);
				
				List<Long> creativeIds = ideasService.uploadIdea(accountId);
				int initCreativeNum = creativeIds.size();
				if (creativeIds.size() == 0) {
					logger.info("user has no idea commit to baidu account");
					continue;
				} else {
					// opera
					Long[] ids = new Long[creativeIds.size()];
					creativeIds.toArray(ids);

					// 这里还需要从数据库获取用户的refresh_token
					UserEntity userInfo = new UserEntity();

					userInfo = accountService.getUserById(accountId);
					String refresh_token = userInfo.getRefreshToken();

					List<String> result = HttpRequest.getAccessToken(refresh_token);
					if (result.size() != 0) {

						String accessToken = result.get(0);

						String reToken = result.get(1);
						userInfo.setRefreshToken(reToken);
						accountService.update(userInfo);

						Map<String, Object> ideas = HttpRequest.getCreate(accessToken, ids);

						String status = ideas.get("status").toString();

						if (status.equals("success")) {

							// 获取数据
							@SuppressWarnings("unchecked")
							List<IdeaEntity> list = (List<IdeaEntity>) ideas.get("data");

							if(list.size()!=0){
								// 批量更新kad创意
								ideasService.updateBatch(list);
							}
							
							// 获取kad中已删除的用户创意id
							for (int a = 0; a < list.size(); a++) {
								long creativeId = list.get(a).getCreativeId();
								creativeIds.remove(creativeId);
							}

							// kad中删除用户百度账户已失效的创意
							if (creativeIds.size() != 0) {
								ideasService.deleteBatchByCreateId(creativeIds);
							}								
							
						} else if (status.equals("failure")) {
							// 不可能出现failure
							String error = ideas.get("reason").toString();
							logger.error(error);
						}
					}else{
						logger.error("user token is not use");
					}
				}

				logger.info("user id is " + accountId + ",creative number is " + initCreativeNum + ",finished");
			}
		}
		logger.info("All operations are finished");
	}
}
